package com.dx.mes.service.process.service;

import static com.dx.mes.common.bean.def.GenericDef.ACTION_FLG_ADD;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_OK;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_UNKNOWN;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_MESG_OK;
import static com.dx.mes.common.bean.def.GenericDef.TRX_OUT;
import static com.dx.mes.common.bean.def.GenericDef.T_FPPWKPOCLM;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import static com.dx.mes.common.bean.def.GenericDef.E_FPPWORKPOSCLM_INPUT_ITEM_EMPT;
import static com.dx.mes.common.bean.def.GenericDef.E_RET_PRD_INFO;
import static com.dx.mes.common.bean.def.GenericDef.E_READ_NOT_FOUND;
import static com.dx.mes.common.bean.def.GenericDef.E_BIS_TOOL;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.dx.common.table.ppt.Bis_tool;
import com.dx.common.table.ppt.Ret_prd_info;
import com.dx.common.table.ppt.Ret_prd_pos;
import com.dx.mes.common.dao.IBisToolDao;
import com.dx.mes.common.dao.IRetPrdInfoDao;
import com.dx.mes.common.dao.IRetWorkPosDao;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.GUIDGenerator;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.LogUtils;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.facade.process.service.IFppworkposclmService;
import com.dx.mes.facade.process.tx.Fppworkposclm.FppworkposclmI;
import com.dx.mes.facade.process.tx.Fppworkposclm.FppworkposclmO;
import com.dx.mes.facade.process.tx.Fppworkposclm.FppworkposclmOA;

@Service("fppworkposclmService")
public class FppworkposclmService implements IFppworkposclmService{
	private static final String TX_NAME = T_FPPWKPOCLM;
	private LogUtils logUtils;
	
	@Autowired
	private IRetWorkPosDao retWorkPosDao;
	@Autowired
	private IRetPrdInfoDao retPrdInfoDao;
	@Autowired
	private IBisToolDao bisToolDao;
			
	@Override
	public String subMainProc(String evt_no, String strInMsg) {
		AppContext.clear();
		AppContext.setCurrServiceName(FppworkposclmService.class.getSimpleName());
		AppContext.setCurrEventNumber(evt_no);
		logUtils = new LogUtils(FppworkposclmService.class);
		logUtils.info("[InTrx:" + strInMsg + "]");
		
		String strOutTrx = "";
		Session session = retWorkPosDao.getCrSession();

		FppworkposclmI inTrx = new FppworkposclmI();
		FppworkposclmO outTrx = new FppworkposclmO();

		outTrx.setTrx_id(TX_NAME);
		outTrx.setType_id(TRX_OUT);
		outTrx.setRtn_code(String.valueOf(RETURN_CODE_OK));
		try {
			inTrx = JacksonUtil.fromJson(strInMsg, FppworkposclmI.class);
			char action_flg = inTrx.getAction_flg().charAt(0);
			switch (action_flg) {
			case ACTION_FLG_ADD:
				addFunc(inTrx,outTrx);
				break;
			case 'T':
				queryTableByPrdId(inTrx,outTrx);
				break;
			default:
				errActionFnc(outTrx);
			}
			if (RETURN_CODE_OK.equals(outTrx.getRtn_code())) {
				session.flush();
			} else {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg(ex.toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} finally {
			strOutTrx = JacksonUtil.toJSONStr(outTrx);
			logUtils.info("[OutTrx:" + strOutTrx + "]");
		}
		return strOutTrx;
	}

	private void queryTableByPrdId(FppworkposclmI inTrx, FppworkposclmO outTrx) {
		
		List<FppworkposclmOA> oaryList = new ArrayList<FppworkposclmOA>();
		String hql = "FROM Ret_prd_pos WHERE 1=1 ";
		if (!Util.isSpaceCheck(inTrx.getPrd_seq_id_fk())) {
			hql += "AND prd_seq_id_fk = '"+inTrx.getPrd_seq_id_fk()+"' order by evt_timestamp";
		}
		List<Ret_prd_pos> posList = retWorkPosDao.find(hql);
		if (!posList.isEmpty()) {
			for(Ret_prd_pos ret_prd_pos : posList){
				FppworkposclmOA oary = new FppworkposclmOA();
				oary.setEvt_timestamp(ret_prd_pos.getEvt_timestamp().toString());
				oary.setEvt_usr(ret_prd_pos.getEvt_usr());
				oary.setPrd_seq_id_fk(ret_prd_pos.getPrd_seq_id_fk());
				oary.setLine_id(ret_prd_pos.getLine_id());
				oary.setTool_id_fk(ret_prd_pos.getTool_id_fk());
				oary.setUnit_id(ret_prd_pos.getUnit_id());
				oaryList.add(oary);
			}
			outTrx.setOary_pos(oaryList);
		}
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	private void errActionFnc(FppworkposclmO outTrx) {
		outTrx.setRtn_code("0000009");
		outTrx.setRtn_mesg("Invalid Action_flg");
		
	}



	private void addFunc(FppworkposclmI inTrx, FppworkposclmO outTrx) {
		String evt_seq_id = GUIDGenerator.javaGUID();                                  
		Timestamp gEvtTimestamp = Util.getCurrentTimestamp();                            
		Ret_prd_pos ret_prd_pos = new Ret_prd_pos();                                     
		    
		if(inTrx.getPrd_seq_id_fk().isEmpty()){
			outTrx.setRtn_code(E_FPPWORKPOSCLM_INPUT_ITEM_EMPT +"");
			outTrx.setRtn_mesg("玻璃代码为空，请确认！");
			return;
		}
		if(inTrx.getTool_id_fk().isEmpty()){
			outTrx.setRtn_code(E_FPPWORKPOSCLM_INPUT_ITEM_EMPT +"");
			outTrx.setRtn_mesg("设备代码为空，请确认！");
			return;
		}
		Ret_prd_info ret_prd_info = retPrdInfoDao.get(inTrx.getPrd_seq_id_fk());
		if(ret_prd_info == null){
			outTrx.setRtn_code(E_RET_PRD_INFO + E_READ_NOT_FOUND +"");
			outTrx.setRtn_mesg("玻璃代码[" + inTrx.getPrd_seq_id_fk()+"]在系统中不存在，请确认！");
			return;
		}
		Bis_tool bis_tool = bisToolDao.get(inTrx.getTool_id_fk());
		if(bis_tool == null){
			outTrx.setRtn_code(E_BIS_TOOL + E_READ_NOT_FOUND +"");
			outTrx.setRtn_mesg("设备代码[" + inTrx.getTool_id_fk()+"]在系统中未维护，请确认！");
			return;
		}
		ret_prd_pos.setEvent_seq_id(evt_seq_id);                                              
		ret_prd_pos.setPrd_seq_id_fk(inTrx.getPrd_seq_id_fk());  
		ret_prd_pos.setTool_id_fk(inTrx.getTool_id_fk());
		ret_prd_pos.setLine_id(inTrx.getLine_id());                                         
		ret_prd_pos.setUnit_id(inTrx.getUnit_id());                                         
		ret_prd_pos.setOpe_typ(inTrx.getOpe_typ());
		ret_prd_pos.setEvt_usr(inTrx.getEvt_usr());
		ret_prd_pos.setEvt_timestamp(gEvtTimestamp);
		retWorkPosDao.save(ret_prd_pos);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

}
